<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
      <el-form-item label="点位" prop="tagName">
        <el-input
            v-model="queryParams.tagName"
            placeholder="请输入点位"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="点位描述" prop="tagNameDescribe">
          <el-input
              v-model="queryParams.tagNameDescribe"
              placeholder="请输入点位描述"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tagNameDict:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:tagNameDict:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tagNameDict:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tagNameDict:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="recordforRef" v-loading="loading" :data="dictList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="点位" align="center" prop="tagName" />
      <el-table-column label="点位描述" align="center" prop="tagNameDescribe" />
      <el-table-column label="点位类型" align="center" prop="tagNameType">
        <template #default="scope">
          <span v-if="scope.row.tagNameType === 0">BOOL</span>
          <span v-else >数值/其他</span>
        </template>
      </el-table-column>
      <el-table-column label="点位值字典" align="center" prop="tagValueDictId" >
        <template #default="{ row }">
          {{ getDictLabel(row.tagValueDictId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:tagNameDict:update']" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:tagNameDict:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改点位字典对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tagRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="点位" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入点位" />
        </el-form-item>
        <el-form-item label="点位描述" prop="tagNameDescribe">
          <el-input v-model="form.tagNameDescribe" placeholder="请输入点位描述" />
        </el-form-item>
        <el-form-item label="点位类型" prop="tagNameType">
          <el-select v-model="form.tagNameType" placeholder="请输入点位类型" >
            <el-option label="" value=""></el-option>
            <el-option label="BOOL" value="0"></el-option>
            <el-option label="数字/其他" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="点位值字典" prop="tagValueDictId">
          <el-select v-model="form.tagValueDictId"  placeholder="请输入点位值字典" clearable :value-key="'value'" >
          <el-option v-for="item in tagValueDict" :key="item.value" :label="item.label" :value="Number(item.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="tagNameDict">
import { ref, onMounted, getCurrentInstance } from "vue";
import { listDict, getDict, delDict, addDict, updateDict } from "@/api/system/tagNameDict.js";
import { mapList } from "@/api/system/dict/type.js";

const { proxy } = getCurrentInstance();
const open = ref(false);
const dictList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const defaultSort = ref({ prop: "createTime", order: "descending" });
const title = ref("");
const tagValueDict = ref([]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  tagName: null,
  tagNameDescribe: null,
});
const rules = ref({
  tagName: [
    {required: true, message: "点位不能为空", trigger: "blur"}
  ],
  tagNameDescribe: [
    {required: true, message: "点位描述不能为空", trigger: "blur"}
  ],
});
const form = ref({});
function reset() {
  form.value = {
    tagName: null,
    tagNameDescribe: null,
    tagNameType: null,
    tagValueDictId: null,
  };
  proxy.resetForm("tagRef");
}
function cancel() {
  open.value = false;
  reset();
}
function getList() {
  loading.value = true;
  listDict(queryParams.value).then(response => {
   dictList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryForm");
  queryParams.value.pageNum = 1;
  proxy.$refs["recordforRef"].sort(defaultSort.value.prop, defaultSort.value.order);
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
  single.value = selection.length !== 1;
}
/** 删除按钮操作 */
function handleDelete(row) {
  const infoIds = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除访问编号为"' + infoIds + '"的数据项?').then(function () {
    return delDict(infoIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
function handleExport() {
  proxy.download('system/tagNameDict/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`);
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
 open.value = true;
 title.value = "添加点位字典";
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  const tagName = row.id || ids.value
  getDict(tagName).then(response => {
    form.value = response.data;
    //open.value = true;
    title.value = "修改点位字典";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["tagRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDict(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDict(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function getDictList(){
  mapList().then(response => {
    console.log(JSON.stringify(response));
    tagValueDict.value = response;
  })}
//创建字典映射（提高查找效率）
const dictMap = computed(() => {
  const map = new Map();
  tagValueDict.value.forEach(item => {
    map.set(item.value, item.label);
  });
  return map;
});
// 获取字典标签的方法
const getDictLabel = (id) => {
  if (!id) return "-";
  console.log("id): " + id);
  return dictMap.value.get(id.toString()) || "未知";
};
onMounted(() => {
  getList();
  getDictList();
})
</script>

<style scoped>

</style>